//
//  OYMultiPartForm.m
//  ObjectiveYouTube
//
//  Created by Tristan O'Tierney on 1/11/08.
//  Copyright 2008 Tristan O'Tierney. All rights reserved.
//

#import <ObjectiveYouTube/ObjectiveYouTube.h>

@interface NSMutableData (OYAdditions)
- (void)appendString:(NSString *)string;
@end

@implementation OYMultiPartForm : NSObject 
- (id)init {
    if ((self = [super init])) {
        unsigned date = [[NSDate date] timeIntervalSinceReferenceDate];
        _boundary = [[NSString alloc] initWithFormat:@"OYMultiPartForm%d", date];
        _contentTypeHeaderValue = [[NSString alloc] initWithFormat:@"multipart/related; boundary=%@", _boundary];
    }

	return self;
}

- (void)dealloc {
    [_boundary release];
	_boundary = nil;
    [_contentTypeHeaderValue release];
	_contentTypeHeaderValue = nil;
	[_fileName release];
	_fileName = nil;
	[_fileType release];
	_fileType = nil;
	[_metaData release];
	_metaData = nil;
    
    [super dealloc];
}

- (void)setMetaData:(NSString *)metaData {
	[metaData retain];
	[_metaData release];
	_metaData = metaData;
}

- (void)setFile:(NSString *)fileName withContentType:(NSString *)type {
	[fileName retain];
	[_fileName release];
	_fileName = fileName;
	
	[type retain];
	[_fileType release];
	_fileType = type;
}

- (NSString *)contentTypeHeaderValue {
    return _contentTypeHeaderValue;
}

- (NSString *)boundry {
	return _boundary;
}

- (NSData *)encodeForm {
    NSMutableData *data = [NSMutableData data];
	
	// Append the metadata
	[data appendString:[NSString stringWithFormat:@"--%@\r\n", _boundary]];
	[data appendString:@"Content-Type: application/atom+xml; charset=UTF-8\r\n\r\n"];
	[data appendString:_metaData];
	[data appendString:[NSString stringWithFormat:@"\r\n--%@\r\n", _boundary]];
    
	// Append the file contents
	[data appendString:[NSString stringWithFormat:@"Content-Type: %@\r\n", _fileType]];
	[data appendString:@"Content-Transfer-Encoding: binary\r\n\r\n"];
	[data appendData:[NSData dataWithContentsOfFile:_fileName]];
	[data appendString:[NSString stringWithFormat:@"\r\n--%@--\r\n", _boundary]];
     
    return data;
}
@end

@implementation NSMutableData (OYAdditions)
- (void)appendString:(NSString *)string {
	NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
	[self appendData:data];
}
@end
